<template>
  <div class="content">
    <!-- 顶部搜索栏 -->
    <div class="top">
      <a-card :bordered="false">
        <a-space :size="size">
          <a-input-search
            v-model:value="user.name"
            style="width: 250px"
            placeholder="请输入分类名"
            size="large"
            @search="onSearch"
          >
            <template #enterButton>
              <a-button style="background-color: #409eff; color: white"
                >查询</a-button
              >
            </template>
          </a-input-search>
          <a-button type="primary" @click="resetParamr" ghost
            ><ReloadOutlined />重置</a-button
          >
          <a-button type="primary" @click="showModal" ghost
            ><PlusCircleOutlined />新增</a-button
          >
          <a-popconfirm
            title="确认删除？"
            ok-text="确认"
            cancel-text="取消"
            @confirm="removeBachById"
            @cancel="cancel"
          >
            <a-button :disabled="!hasSelected" type="primary" danger ghost
              ><DeleteOutlined />批量删除</a-button
            >
          </a-popconfirm>
        </a-space>
      </a-card>
    </div>

    <!-- 表格数据展示 -->
    <div class="table">
      <a-card :bordered="false">
        <div>
          <a-table
            :row-selection="{
              selectedRowKeys: state.selectedRowKeys,
              onChange: onSelectChange,
            }"
            :data-source="data"
            :pagination="false"
            :scroll="{ x: 200, y: 500 }"
            :loading="loading"
          >
            <a-table-column key="name" title="分类名" data-index="name" />
            <a-table-column key="number" title="数量" data-index="number" />
            <a-table-column key="id" title="操作">
              <template #default="{ record }">
                <div style="display: flex">
                  <div>
                    <a-button
                      v-if="record.parentId === '0' ? true : false"
                      @click="saveCategory(record.id)"
                      type="link"
                      ghost
                      >新增</a-button>
                  </div>
                  <div style="margin-left: 10px">
                    <a-button @click="edit(record.key)" type="link" ghost
                      >修改</a-button>
                  </div>
                  <div style="margin-left: 10px">
                    <a-popconfirm
                      title="确认删除？"
                      ok-text="确认"
                      cancel-text="取消"
                      @confirm="remove(record.key)"
                      @cancel="cancel"
                    >
                      <a-button type="link" ghost danger>
                        删除
                      </a-button>
                    </a-popconfirm>
                  </div>
                </div>
              </template>
            </a-table-column>
          </a-table>
        </div>
        <!-- <div style="padding-top: 20px; margin-left: 400px">
          <a-pagination
            v-model:current="pageNo"
            v-model:page-size="pageSize"
            :total="total"
            @change="handlePageChange"
            :show-total="(total) => `共 ${total} 条`"
          />
        </div> -->
      </a-card>
    </div>

    <!-- 新增弹出框 -->
    <div>
      <a-modal
        v-model:open="open"
        @cancel="handleCancel"
        title="新增分类"
        :footer="null"
      >
        <div style="padding: 30px 0 20px 50px">
          <a-form
            ref="formRef"
            :model="category"
            :rules="rules"
            :label-col="labelCol"
            :wrapper-col="wrapperCol"
          >
            <a-form-item ref="name" label="分类名" name="name">
              <a-input
                maxlength="10"
                v-model:value="category.name"
                size="large"
              />
            </a-form-item>
            <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
              <a-button type="primary" @click="save">保存</a-button>
              <a-button style="margin-left: 10px" @click="handleCancel"
                >取消</a-button
              >
            </a-form-item>
          </a-form>
        </div>
      </a-modal>
    </div>
  </div>
</template>

<script setup>
import {
  ReloadOutlined,
  PlusCircleOutlined,
  DeleteOutlined
} from "@ant-design/icons-vue";
import { ref, reactive, computed, onMounted } from "vue";
import { message } from "ant-design-vue";
import {
  saveAdmin,
  list,
  echo,
  update,
  removeBatchByKeys,
} from "@/api/category";

const size = ref(20);
const data = ref([{}]);
const category = ref({
  key: null,
  name: "",
  pid: null,
});

const loading = ref(true);
onMounted(() => {
  setInterval(() => {
    loading.value = false;
  }, 1000);
  getAdmins();
});

//根据用户名进行模糊查询,没办法参数必须是一个对象
const user = ref({
  name: "",
});
//异步请求管理员数据
function getAdmins() {
  list(user.value).then((res) => {
    if (res.code === 200 && res.data != null) {
      data.value = res.data;
    }
  });
}

//管理员数据模糊查询
function onSearch(searchValue) {
  user.value.name = searchValue;
  getAdmins();
}

//重置模糊查询数据
function resetParamr() {
  user.value.name = "";
  getAdmins();
}

//新增管理员弹框
const open = ref(false);
const showModal = () => {
  open.value = true;
};

function saveCategory(parentId) {
  category.value.pid = parentId;
  open.value = true;
}

//新增管理员操作
function save() {
  formRef.value
    .validate()
    .then(() => {
      //新增管理员
      if (category.value.key === null) {
        saveAdmin(category.value).then((res) => {
          if (res.code === 200) {
            message.success("新增成功！");
            //重新加载管理员数据
            getAdmins();
            open.value = false;
            category.value = {};
            category.value.key = null;
          }
        });
      } else {
        //修改管理员
        update(category.value).then((res) => {
          if (res.code === 200) {
            message.success("修改成功！");
            //重新加载管理员数据
            getAdmins();
            open.value = false;
            category.value = {};
            category.value.key = null;
          }
        });
      }
    })
    .catch((error) => {
      console.log("error", error);
    });
}

//取消新增管理员操作
function handleCancel() {
  open.value = false;
  category.value = {};
  category.value.key = null;
}

//管理员修改操作
function edit(id) {
  echo(id).then((res) => {
    if (res.code === 200 && res.data != null) {
      category.value = res.data;
      category.value.pid = category.value.key;
      open.value = true;
    }
  });
}

//管理员确认删除回调操作
function remove(id) {
  removeBatchByKeys(id).then((res) => {
    if (res.code === 200) {
      message.success("删除成功！");
      //重新加载分页数据
      getAdmins();
    }
  });
}

//管理员取消删除回调操作
function cancel() {
  message.warning("取消删除！");
}

//数据校验
const formRef = ref();
const labelCol = {
  span: 5,
};
const wrapperCol = {
  span: 13,
};
const rules = {
  name: [
    {
      required: true,
      message: "请输入用户名",
      trigger: "change",
    },
    {
      min: 2,
      max: 10,
      message: "长度为2~10个字符",
      trigger: "blur",
    },
  ],
  remark: [
    {
      required: true,
      message: "请输入品牌简介",
      trigger: "blur",
    },
  ],
  image: [
    {
      required: true,
      message: "请上传品牌图",
      trigger: "blur",
    },
  ],
};

//存储批量管理员id
const state = reactive({
  selectedRowKeys: [],
});
//当有一个或多个管理员被选中时触发按钮
const hasSelected = computed(() => state.selectedRowKeys.length > 0);
//批量删除管理员
const removeBachById = () => {
  setTimeout(() => {
    state.selectedRowKeys = [];
  }, 1000);
  //删除后做操作
  removeBatchByKeys(state.selectedRowKeys).then((res) => {
    if (res.code === 200) {
      message.success("删除成功！");
      //重新加载分页数据
      getAdmins();
    }
  });
};
//当选中行改变时触发
const onSelectChange = (selectedRowKeys) => {
  state.selectedRowKeys = selectedRowKeys;
};
</script>

<style scoped>
.options {
  margin-top: 10px;
}

.table {
  margin-top: 10px;
}

.avatar-uploader > .ant-upload {
  width: 50px;
  height: 50px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}

:deep(.ant-card-body) {
  padding: 10px;
}
</style>>
